require(['init'], function () {

  var folderId;
  var folderName;

  function refresh() {
    $('#J_breadcrumb li.active').click()
  }

  /**
   * [cloudFileUpload description]
   * @return {[type]} [description]
   */
  function cloudFileUpload() {
    var coverUploadInput = new UploadInput({
      formData: {
        pid: (folderId || 0)
      },
      $dom: $('#J_fileupload'),
      done: function (uploadSrc) {
        refresh();
      }
    });
  }

  /**
   * [getFolderList description]
   * @param  {[type]} fid   [description]
   * @param  {[type]} fname [description]
   * @return {[type]}       [description]
   */
  function getFolderList(fid, fname) {
    fid || (fid = 0);
    fname || (fname = '全部文件')
    folderId = fid;

    if(fid == 0) {
      $('#J_breadcrumb li.active').on('click', function () {
        $(this).nextAll().remove();
        getFolderList(fid, fname)
      })
    } else {
      var $curBread = $('<li><a>'+ fname +'</a></li>')
      $curBread.on('click', function () {
        $(this).prev().nextAll().remove();
        getFolderList(fid, fname)
      })
      .appendTo('#J_breadcrumb')
      .singleActive();
    }


    ajaxMethod({
      url: '/api/cloud/folder/' + fid,
      success: function (data) {
        cloudFileUpload()

        var $folderListTable = $('#J_folderList').html('')
        var $thead = $('<thead>\
          <tr>\
            <th width="5">\
              <span class="icon icon-size-16 icon-checkbox" data-type="checkbox">\
                <input type="checkbox" name="folderAll">\
              </span>\
            </th>\
            <th class="text-left">\
              <span class="name">'+i18next.t('cloud.filename')+'</span>\
            </th>\
            <th class="text-left" width="150">'+i18next.t('table.handle')+'</th>\
          </tr>\
        </thead>').appendTo($folderListTable)

        //文件夹解析
        var $tbody = $('<tbody></tbody>').appendTo($folderListTable)
        $.each(data.folder_list, function (index, item) {

          var $classItem = $('<tr class="enroll"></tr>')

          var $check = $(
            '<td width="5">\
              <span class="icon icon-size-16 icon-checkbox" data-type="checkbox">\
                <input type="checkbox" name="folder" >\
              </span>\
            </td>'
          ).appendTo($classItem);

          var $folderName = $(
            '<td class="file-td">\
              <span data-folderid="'+ item.folder_id +'">\
                <span class="file">\
                  <span class="icon icon-size-24 icon-clouddisk-folder'+ (item.is_system_folder ? '-system' : '')  +'"></span>\
                  <span class="name">'+ item.folder_name +'</span>\</span>\
              </span>\
            </td>'
          ).appendTo($classItem);

          $folderName.on('click', function () {
            console.log(1);
            getFolderList(item.folder_id, item.folder_name);
          })

          var $folderHandler = $(
            '<td>\
              <div class="hide">\
                <span class="btn btn-primary btn-sm btn-inverse J_rename" style="margin-right:5px">'+i18next.t('cloud.rename')+'</span>\
                <span class="btn btn-danger btn-sm btn-inverse J_delete">'+i18next.t('table.delete')+'</span>\
              </div>\
            </td>'
          ).appendTo($classItem);

          $folderHandler.find('.J_rename').on('click', function () {

            var $input = $('<input type="text" class="form-control" value="'+ item.folder_name +'" style="margin: 20px;width:250px;"/>');
            var beforeVal = $.trim($input.val());

            new PopUpBox({
              type:'dom',
              style:'default',
              submitBtnType:'confirm',
              titleText:i18next.t('cloud.rename'),
              content: $input,
              show: true,
              callback: {
                yes: function () {
                  var trimVal = $.trim($input.val())
                  if(!trimVal) {
                    _Tips(i18next.t('popupbox.noempty'));
                    return false;
                  }

                  if(beforeVal == trimVal) {
                    return true;
                  }

                  ajaxMethod({
                    url: '/api/cloud/folder/' + item.folder_id,
                    method: 'put',
                    data: {
                      fid: item.folder_id,
                      name: trimVal
                    },
                    success: function (data, status) {
                      if(status.code == 0) {
                        refresh();
                      }
                    }
                  })

                }
              },
              position: {
                width: 400,
                height: 200
              }
            })


          })

          $folderHandler.find('.J_delete').on('click', function () {
            new PopUpBox({
              type:'alert',
              style:'default',
              submitBtnType:'confirm',
              titleText:i18next.t('popupbox.systemmessages'),
              content: '<p style="padding:30px"> '+i18next.t('popupbox.delfile')+'</p>',
              show: true,
              callback: {
                yes: function () {
                  ajaxMethod({
                    url: '/api/cloud/folder/' + item.folder_id,
                    method: 'delete',
                    success: function (data, status) {
                      if(status.code == 0) {
                        refresh();
                      }
                    }
                  })

                }
              },
              position: {
                width: 420,
                height: 200
              }
            })
          })

          $tbody.append($classItem)
        })

        //文件解析
        $.each(data.file_list, function (index, item) {
          //<span class="icon icon-size-24 icon-clouddisk-folder'+ (item.is_system_folder ? '-system' : '')  +'"></span>\

          var $classItem = $('<tr class="enroll"></tr>')

          var $check = $(
            '<td width="5">\
              <span class="icon icon-size-16 icon-checkbox" data-type="checkbox">\
                <input type="checkbox" name="file">\
              </span>\
            </td>'
          ).appendTo($classItem);

          var $folderName = $(
            '<td class="file-td">\
              <span data-fileid="'+ item.id +'">\
                <span class="file">\
                  <span>'+ item.file_name +'</span>\
                </span>\
              </span>\
            </td>'
          ).appendTo($classItem);
          var $folderHandler = $(
            '<td>\
              <div class="hide">\
                <span class="btn btn-sm btn-primary  btn-inverse J_rename" style="margin-right:5px">'+i18next.t('cloud.rename')+'</span>\
                <span class="btn btn-sm btn-danger  btn-inverse J_delete">'+i18next.t('table.delete')+'</span>\
              </div>\
            </td>'
          ).appendTo($classItem);

          $folderHandler.find('.J_rename').on('click', function () {

            var tempArr = item.file_name.split('.');
            tempArr.pop()

            var $input = $('<input type="text" class="form-control" value="'+ tempArr.join('.') +'" style="margin: 20px;width:250px;"/>');
            var beforeVal = tempArr.join('.');

            new PopUpBox({
              type:'dom',
              style:'default',
              submitBtnType:'confirm',
              titleText:i18next.t('cloud.rename'),
              content: $input,
              show: true,
              callback: {
                yes: function () {
                  var trimVal = $.trim($input.val())
                  if(!trimVal) {
                    _Tips(i18next.t('popupbox.noempty'));
                    return false;
                  }

                  if(beforeVal == trimVal) {
                    return true;
                  }

                  ajaxMethod({
                    url: '/api/cloud/file/' + item.id,
                    method: 'put',
                    data: {
                      fid: item.id,
                      name: trimVal
                    },
                    success: function (data, status) {
                      if(status.code == 0) {
                        refresh();
                      }
                    }
                  })

                }
              },
              position: {
                width: 400,
                height: 200
              }
            })


          })

          $folderHandler.find('.J_delete').on('click', function () {
            new PopUpBox({
              type:'alert',
              style:'default',
              submitBtnType:'confirm',
              titleText:i18next.t('popupbox.confirmdelete'),
              content: '<p style="padding:30px"> '+i18next.t('popupbox.delfile')+'</p>',
              show: true,
              callback: {
                yes: function () {
                  ajaxMethod({
                    url: '/api/cloud/file/' + item.id,
                    method: 'delete',
                    success: function (data, status) {
                      if(status.code == 0) {
                        refresh();
                      }
                    }
                  })

                }
              },
              position: {
                width: 400,
                height: 200
              }
            })
          })

          $tbody.append($classItem)
        })

      }
    })
  }

  cloudFileUpload();
  getFolderList(folderId, folderName)

  $('#J_createFolder').on('click', function () {
    var $newFolder = $(
      '<td>\
        <span>\
          <span class="icon icon-size-24 icon-clouddisk-folder"></span>\
          <span class="name"><input type="text" value="新建文件夹" autofocus class="input-focus"/></span>\
          <span class="icon icon-size-16 icon-checked-true" style="cursor: pointer;"></span>\
          <span class="icon icon-size-16 icon-close" style="cursor: pointer;"></span>\
        </span>\
      <td>'
    )
    $newFolder.find('input').val(i18next.t('cloud.newfolder'))

    var $yes = $newFolder.find('.icon-checked-true')
    $yes.on('click', function () {
      var inputVal = $.trim($newFolder.find('input').val());
      if(!inputVal) {
        _Tips(i18next.t('popupbox.foldernoempty'));
        return;
      }
      ajaxMethod({
        url: '/api/cloud/folder',
        method: 'post',
        data: {
          pid: folderId,
          name: inputVal
        },
        success: function (data, status) {
          if(status.code == 0) {
            refresh();
          }
        }
      })
    })
    var $no = $newFolder.find('.icon-close')
    $no.on('click', function () {
      $(this).closest('tr').remove()
    })

    var $tr = $('<tr></tr>')
    $tr.append('<td width="4"></td>')
    $tr.append($newFolder);

    $('#J_folderList').find('tbody').prepend($tr)
    $newFolder.find('input').select()

  })
})
